package org.cocos2dx.javascript;

import android.content.Context;
import android.util.Log;

import com.bytedance.sdk.openadsdk.AdSlot;
import com.bytedance.sdk.openadsdk.TTAdConstant;
import com.bytedance.sdk.openadsdk.TTAdManager;
import com.bytedance.sdk.openadsdk.TTAdNative;
import com.bytedance.sdk.openadsdk.TTAppDownloadListener;
import com.bytedance.sdk.openadsdk.TTRewardVideoAd;
import com.bytedance.sdk.openadsdk.TTAdConfig;
import com.bytedance.sdk.openadsdk.TTAdSdk;
import com.byteedu.yyb.landlord.R;

import org.json.JSONException;
import org.json.JSONObject;

public class RewardVideo {
    private static String TAG = "RewardVideo";
    private TTAdNative mTTAdNative = null;
    private TTRewardVideoAd mttRewardVideoAd = null;
    private AppActivity mApp = null;
    private static boolean mHasShowDownloadActive = false;
    private static RewardVideo sInstance = null;

    public  static RewardVideo getInstance(){
        if (sInstance == null){
            sInstance= new RewardVideo();
        }

        return sInstance;
    }

    public void init(AppActivity app){
        mApp = app;
        //穿山甲SDK初始化
        TTAdSdk.init(app, new TTAdConfig.Builder()
            .appId(app.getResources().getString(R.string.bytedance_appID))
            .appName(app.getResources().getString(R.string.app_name))
            .titleBarTheme(TTAdConstant.TITLE_BAR_THEME_DARK)
            .useTextureView(true) //使用TextureView控件播放视频,默认为SurfaceView,当有SurfaceView冲突的场景，可以使用TextureView
            .allowShowNotify(true) //是否允许sdk展示通知栏提示
            .debug(false) //测试阶段打开，可以通过日志排查问题，上线时去除该调用
            .directDownloadNetworkType(TTAdConstant.NETWORK_STATE_WIFI) //允许直接下载的网络状态集合
            .supportMultiProcess(true)//是否支持多进程
            .asyncInit(true) //异步初始化sdk，开启可减少初始化耗时
            .needClearTaskReset()
            //.httpStack(new MyOkStack3())//自定义网络库，demo中给出了okhttp3版本的样例，其余请自行开发或者咨询工作人员。
            .build());

        //step1:初始化sdk
        TTAdManager ttAdManager = TTAdSdk.getAdManager();
        //step2:(可选，强烈建议在合适的时机调用):申请部分权限，如read_phone_state,防止获取不了imei时候，下载类广告没有填充的问题。
        ttAdManager.requestPermissionIfNecessary(app);
        //step3:创建TTAdNative对象,用于调用广告请求接口
        mTTAdNative = ttAdManager.createAdNative(app);
    }

    public void loadAd(final String codeId,final String userID){
        //step4:创建广告请求参数AdSlot,具体参数含义参考文档
        AdSlot adSlot = new AdSlot.Builder()
                .setCodeId(codeId)
                .setSupportDeepLink(true)
                .setImageAcceptedSize(1080, 1920)
                .setRewardAmount(1)  //奖励的数量
                .setUserID(userID)//用户id,必传参数
                .setOrientation(TTAdConstant.VERTICAL) //必填参数，期望视频的播放方向：TTAdConstant.HORIZONTAL 或 TTAdConstant.VERTICAL
                .build();

        //step5:请求广告
        mTTAdNative.loadRewardVideoAd(adSlot, new TTAdNative.RewardVideoAdListener() {
            @Override
            public void onError(int code, String message) {
                Log.e(TAG, message);
            }

            //视频广告加载后，视频资源缓存到本地的回调，在此回调后，播放本地视频，流畅不阻塞。
            @Override
            public void onRewardVideoCached() {
                Log.e(TAG, "rewardVideoAd video cached");
            }

            //视频广告的素材加载完毕，比如视频url等，在此回调后，可以播放在线视频，网络不好可能出现加载缓冲，影响体验。
            @Override
            public void onRewardVideoAdLoad(TTRewardVideoAd ad) {
                Log.e(TAG, "rewardVideoAd loaded");
                mttRewardVideoAd = ad;
                mttRewardVideoAd.setRewardAdInteractionListener(new TTRewardVideoAd.RewardAdInteractionListener() {

                    @Override
                    public void onAdShow() {
                        ToolHelp.getInstance().callJS("LoadFinished","");
                        Log.d(TAG, "rewardVideoAd show");
                    }

                    @Override
                    public void onAdVideoBarClick() {
                        Log.d(TAG, "rewardVideoAd bar click");
                    }

                    @Override
                    public void onAdClose() {
                        Log.d(TAG, "rewardVideoAd close");
                    }

                    //视频播放完成回调
                    @Override
                    public void onVideoComplete() {
                        Log.d(TAG,"rewardVideoAd complete");
                    }

                    @Override
                    public void onVideoError() {
                        Log.d(TAG,"rewardVideoAd error");
                    }

                    //视频播放完成后，奖励验证回调，rewardVerify：是否有效，rewardAmount：奖励梳理，rewardName：奖励名称
                    @Override
                    public void onRewardVerify(boolean rewardVerify, int rewardAmount, String rewardName,int code,String msg) {
                        Log.d(TAG,"rewardVideoAd rewardVerify");
                        String data;
                        if (rewardVerify){
                            JSONObject jsonObject = new JSONObject();
                            try {
                                jsonObject.put("RewardName", rewardName);
                                jsonObject.put("RewardCount", rewardAmount);
                                jsonObject.put("flag", "RewardVideo");
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                            data = jsonObject.toString();
                        } else {
                            data = String.format("RewardVerify error.code=(%d),msg=%s",code,msg);
                        }
                        ToolHelp.getInstance().callJS("RewardVerify",data);
                    }

                    @Override
                    public void onSkippedVideo() {
                    }
                });
                mttRewardVideoAd.setDownloadListener(new TTAppDownloadListener() {
                    @Override
                    public void onIdle() {
                        mHasShowDownloadActive = false;
                    }

                    @Override
                    public void onDownloadActive(long totalBytes, long currBytes, String fileName, String appName) {
                        if (!mHasShowDownloadActive) {
                            mHasShowDownloadActive = true;
                            //TToast.show(RewardVideoActivity.this, "下载中，点击下载区域暂停", Toast.LENGTH_LONG);
                        }
                    }

                    @Override
                    public void onDownloadPaused(long totalBytes, long currBytes, String fileName, String appName) {
                        //TToast.show(RewardVideoActivity.this, "下载暂停，点击下载区域继续", Toast.LENGTH_LONG);
                    }

                    @Override
                    public void onDownloadFailed(long totalBytes, long currBytes, String fileName, String appName) {
                        //TToast.show(RewardVideoActivity.this, "下载失败，点击下载区域重新下载", Toast.LENGTH_LONG);
                    }

                    @Override
                    public void onDownloadFinished(long totalBytes, String fileName, String appName) {
                        //TToast.show(RewardVideoActivity.this, "下载完成，点击下载区域重新下载", Toast.LENGTH_LONG);
                    }

                    @Override
                    public void onInstalled(String fileName, String appName) {
                        //TToast.show(RewardVideoActivity.this, "安装完成，点击下载区域打开", Toast.LENGTH_LONG);
                    }
                });
                mApp.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        mttRewardVideoAd.showRewardVideoAd(mApp,TTAdConstant.RitScenes.CUSTOMIZE_SCENES,"scenes_test");
                        mttRewardVideoAd = null;
                        Log.d("穿山甲广告展示","mttRewardVideoAd不为空，开始播放");
                    }
                });
            }
        });}
}
